package com.gomore.opple.module.main.shoppingcar.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Rect;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gomore.opple.R;
import com.gomore.opple.service.SelectAllClickListener;
import com.gomore.opple.utils.BigDecimalUtils;
import com.gomore.opple.web.cgform.goods.view.VOResellerGoodsEntity;
import com.gomore.opple.web.cgform.shopcart.entity.TOShopcartEntity;
import com.gomore.opple.widgets.adapter.CommonAdapter;
import com.gomore.opple.widgets.adapter.ViewHolder;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by asus on 2017/5/16.
 */
public class ShoppingCarAdapter extends CommonAdapter<TOShopcartEntity> {
    Context mContext;
    Activity activity;
    BigDecimal lowestPricePrecent;
    // 用来控制CheckBox的选中状况
    public static HashMap<Integer, Boolean> isSelected;
    private int size;
    private SelectAllClickListener selectAllClickListener;

    public void setAllClickListener(SelectAllClickListener selectAllClickListener) {
        this.selectAllClickListener = selectAllClickListener;
    }

    public ShoppingCarAdapter(Context context, Activity activity, int layoutId, List<TOShopcartEntity> toGoodsEntityList, BigDecimal lowest) {
        super(context, layoutId, toGoodsEntityList);
        mContext = context;
        this.activity = activity;
        lowestPricePrecent = lowest;
        isSelected = new HashMap<>();
        size = toGoodsEntityList.size();
        initDate();
    }

    // 初始化isSelected的数据
    public void initDate() {
        for (int i = 0; i < size; i++) {
            getIsSelected().put(i, false);
        }
    }

    // 初始化选中isSelected的数据
    public void initDateToCheck() {
        for (int i = 0; i < size; i++) {
            getIsSelected().put(i, true);
        }
    }

    public static HashMap<Integer, Boolean> getIsSelected() {
        return isSelected;
    }

    public static void setIsSelected(HashMap<Integer, Boolean> isSelected) {
        ShoppingCarAdapter.isSelected = isSelected;
    }

    @Override
    protected void convert(ViewHolder holder, final TOShopcartEntity toShopcartEntity, final int position) {
        CheckBox image_box = holder.getView(R.id.image_box);
        ImageView image_icon = holder.getView(R.id.image_icon);
        TextView name = holder.getView(R.id.name);
        TextView code = holder.getView(R.id.code);
        TextView tag_price = holder.getView(R.id.tag_price);
        TextView done_price = holder.getView(R.id.done_price);
        TextView total = holder.getView(R.id.total);
        ImageView min = holder.getView(R.id.min);
        TextView good_quanity = holder.getView(R.id.good_quanity);
        ImageView add = holder.getView(R.id.add);
        // 根据isSelected来设置checkbox的选中状况
        image_box.setChecked(getIsSelected().get(position));
        image_box.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isSelected.get(position)) {
                    isSelected.put(position, false);
                    setIsSelected(isSelected);
                } else {
                    isSelected.put(position, true);
                    setIsSelected(isSelected);
                }
                selectAllClickListener.SelectAll();
                notifyDataSetChanged();
            }
        });

        if (toShopcartEntity.getGoods() == null) {
            return;
        }
        VOResellerGoodsEntity voResellerGoodsEntity = toShopcartEntity.getGoods();
        String url = "demo";
        if (voResellerGoodsEntity.getPictures() != null) {
            String[] urls = voResellerGoodsEntity.getPictures().split(",");
            url = urls[0];
        }
        Glide.with(mContext)
                .load(url)
                .asBitmap()
                .placeholder(R.mipmap.goods_place)
                .into(image_icon);
        if (voResellerGoodsEntity.getName() != null) {
            name.setText(voResellerGoodsEntity.getName());
        }
        if (voResellerGoodsEntity.getCode() != null) {
            code.setText(voResellerGoodsEntity.getCode());
        }
        if (voResellerGoodsEntity.getTagPrice() != null) {
            BigDecimal str = BigDecimalUtils.forMate(voResellerGoodsEntity.getTagPrice());
            tag_price.setText("¥" + str.toString());
        }
        //显示成交价
        BigDecimal str = null;
        if (toShopcartEntity.getCostPrice() != null) {
            str = BigDecimalUtils.forMate(toShopcartEntity.getCostPrice());
            done_price.setText(str.toString());
        }
        //显示商品数量
        BigDecimal bigDecimal = new BigDecimal(toShopcartEntity.getGoodsNum());
        good_quanity.setText("" + toShopcartEntity.getGoodsNum());
        //显示产品金额
        if (str != null) {
            BigDecimal totalBigdecimal = str.multiply(bigDecimal);
            total.setText("¥" + totalBigdecimal.toString());
        }

        done_price.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDonePriceDialog(toShopcartEntity, position);
            }
        });

        min.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int number = toShopcartEntity.getGoodsNum();
                if (number > 1) {
                    number--;
                    toShopcartEntity.setGoodsNum(number);
                    notifyDataSetChanged();
                    if (getIsSelected().get(position)) {
                        selectAllClickListener.SelectAll();
                    }
                    selectAllClickListener.updateCostPrice(toShopcartEntity.getId(), toShopcartEntity.getCostPrice().toString(),
                            toShopcartEntity.getGoods().getId(), toShopcartEntity.getGoodsNum().toString(), true);
                }
            }
        });

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int number = toShopcartEntity.getGoodsNum();
                BigDecimal bigDecimalInput = new BigDecimal(number);
                BigDecimal bigDecimal = new BigDecimal(toShopcartEntity.getGoods().getInv());
                int compare = bigDecimalInput.compareTo(bigDecimal);
                if (compare > 0) {
                    Toast.makeText(mContext, "商品输入数量不能超过库存数量", Toast.LENGTH_SHORT).show();
                    return;
                }
                number++;
                toShopcartEntity.setGoodsNum(number);
                notifyDataSetChanged();
                if (getIsSelected().get(position)) {
                    selectAllClickListener.SelectAll();
                }
                selectAllClickListener.updateCostPrice(toShopcartEntity.getId(), toShopcartEntity.getCostPrice().toString(),
                        toShopcartEntity.getGoods().getId(), toShopcartEntity.getGoodsNum().toString(), true);
            }
        });

        good_quanity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(toShopcartEntity, position);
            }
        });
    }

    private void showDonePriceDialog(final TOShopcartEntity toShopcartEntity, final int position) {
        View layout = LayoutInflater.from(mContext).inflate(R.layout.done_price_dialog, null);
        TextView dialog_textview_text = (TextView) layout.findViewById(R.id.dialog_textview_text);
        dialog_textview_text.setText("修改成交价");
        final EditText remark = (EditText) layout.findViewById(R.id.remark);
        TextView dialog_cancel = (TextView) layout.findViewById(R.id.dialog_cancel);
        TextView dialog_confirm = (TextView) layout.findViewById(R.id.dialog_confirm);
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setView(layout);
        builder.setCancelable(false);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        if (toShopcartEntity.getCostPrice() != null) {
            String str = toShopcartEntity.getCostPrice().toString();
            remark.setText(str);
            remark.setSelection(str.length());
        }
        //自动弹出软键盘
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                showSoft();
            }
        }, 300);
        remark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String str = editable.toString().trim();
                if (!TextUtils.isEmpty(str) && (str.startsWith("0") || str.startsWith("."))) {
                    remark.setText("");
                }
            }
        });

        dialog_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                hideSoft();
            }
        });

        dialog_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(remark.getText().toString().trim())) {
                    Toast.makeText(mContext, "请输入成交价", Toast.LENGTH_SHORT).show();
                    return;
                }
                BigDecimal bigDecimal = null;
                try {
                    //将字符串转化为BigDecimal类型，并保存两位小数
                    bigDecimal = BigDecimalUtils.forMate(new BigDecimal(remark.getText().toString().trim()));
                } catch (Exception e) {
                    Toast.makeText(mContext, "输入的成交价包含非法字符", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (toShopcartEntity.getGoods() == null) {
                    return;
                }
                if (toShopcartEntity.getGoods().getTagPrice() == null) {
                    Toast.makeText(mContext, mContext.getResources().getString(R.string.guide_price_null), Toast.LENGTH_SHORT).show();
                    return;
                }
                //最低成交价
                BigDecimal lowesrPrice = toShopcartEntity.getGoods().getGuidePrice().multiply(lowestPricePrecent)
                        .divide(new BigDecimal(100));
                int com = bigDecimal.compareTo(lowesrPrice);
                if (com == -1) {
                    Toast.makeText(mContext, mContext.getResources().getString(R.string.no_promission), Toast.LENGTH_SHORT).show();
                    return;
                }
                toShopcartEntity.setCostPrice(bigDecimal);
                alertDialog.dismiss();
                notifyDataSetChanged();
                if (getIsSelected().get(position)) {
                    selectAllClickListener.SelectAll();
                }
                selectAllClickListener.updateCostPrice(toShopcartEntity.getId(), toShopcartEntity.getCostPrice().toString(),
                        toShopcartEntity.getGoods().getId(), toShopcartEntity.getGoodsNum().toString(), false);
                hideSoft();
            }
        });
    }

    private void showDialog(final TOShopcartEntity toShopcartEntity, final int position) {
        View layout = LayoutInflater.from(mContext).inflate(R.layout.number_dialog, null);
        TextView dialog_textview_text = (TextView) layout.findViewById(R.id.dialog_textview_text);
        dialog_textview_text.setText("修改下单数量");
        ImageView dialog_goods_minus = (ImageView) layout.findViewById(R.id.dialog_goods_minus);
        final EditText dialog_goods_number = (EditText) layout.findViewById(R.id.dialog_goods_number);
        ImageView dialog_goods_add = (ImageView) layout.findViewById(R.id.dialog_goods_add);
        TextView dialog_cancel = (TextView) layout.findViewById(R.id.dialog_cancel);
        TextView dialog_confirm = (TextView) layout.findViewById(R.id.dialog_confirm);
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setView(layout);
        builder.setCancelable(false);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        dialog_goods_number.setText(toShopcartEntity.getGoodsNum().toString());
        dialog_goods_number.setSelection(toShopcartEntity.getGoodsNum().toString().length());
        //自动弹出软键盘
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                showSoft();
            }
        }, 300);
        dialog_goods_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String str = editable.toString().trim();
                if (!TextUtils.isEmpty(editable.toString().trim())) {
                    if (str.startsWith("0")) {
                        dialog_goods_number.setText("");
                    } else {
                        BigDecimal bigDecimalInput = new BigDecimal(editable.toString().trim());
                        BigDecimal bigDecimal = new BigDecimal(toShopcartEntity.getGoods().getInv());
                        int compare = bigDecimalInput.compareTo(bigDecimal);
                        if (compare > 0) {
                            Toast.makeText(mContext, "商品输入数量不能超过库存数量", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        toShopcartEntity.setGoodsNum(bigDecimalInput.intValue());
                    }
                }
            }
        });
        dialog_goods_minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int number = toShopcartEntity.getGoodsNum();
                if (number > 1) {
                    number--;
                    toShopcartEntity.setGoodsNum(number);
                    dialog_goods_number.setText("" + number);
                }
            }
        });


        dialog_goods_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int number = toShopcartEntity.getGoodsNum();
                BigDecimal bigDecimalInput = new BigDecimal(number);
                BigDecimal bigDecimal = new BigDecimal(toShopcartEntity.getGoods().getInv());
                int compare = bigDecimalInput.compareTo(bigDecimal);
                if (compare > 0) {
                    Toast.makeText(mContext, "商品输入数量不能超过库存数量", Toast.LENGTH_SHORT).show();
                    return;
                }
                number++;
                toShopcartEntity.setGoodsNum(number);
                dialog_goods_number.setText("" + number);
            }
        });

        dialog_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                hideSoft();
            }
        });

        dialog_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(dialog_goods_number.getText().toString().trim())) {
                    Toast.makeText(mContext, "请输入下单数量", Toast.LENGTH_SHORT).show();
                    return;
                }
                notifyDataSetChanged();
                if (getIsSelected().get(position)) {
                    selectAllClickListener.SelectAll();
                }
                alertDialog.dismiss();
                selectAllClickListener.updateCostPrice(toShopcartEntity.getId(), toShopcartEntity.getCostPrice().toString(),
                        toShopcartEntity.getGoods().getId(), toShopcartEntity.getGoodsNum().toString(), true);
                hideSoft();
            }
        });
    }

    /**
     * 显示软键盘
     */
    private void showSoft() {
        ((InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE))
                .toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 隐藏软键盘
     */
    private void hideSoft() {
        if (isSoftShowing()) {
            ((InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE))
                    .toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 判断软键盘是否隐藏
     *
     * @return
     */
    private boolean isSoftShowing() {
        //获取当前屏幕内容的高度
        int screenHeight = activity.getWindow().getDecorView().getHeight();
        //获取View可见区域的bottom
        Rect rect = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        return screenHeight - rect.bottom != 0;
    }
}
